package com.pb.infra.oth.service;

import com.pb.infra.oth.exception.BizException;
import com.pb.infra.oth.util.SpringContextUtil;
import com.pb.infra.oth.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 获取不重复序号
 * @author liudebao
 */
@Service
@Configuration
@Slf4j
public class SequenceGeneratorService {

    private static HashMap<String, UniqueTableService> keyList = new HashMap(60);

    /**
     * 每次缓冲数量
     */
    private static long POOL_SIZE = 5L;

    @Value("${sequence.poolsize}")
    public void setPoolSize(long poolSize) {
        POOL_SIZE = poolSize;
    }

    /**
     * 获取下一个序号
     * @param seqType 序号类型
     * @param prefix 前缀
     * @return 序号值
     */
    public String getNextIdStr(String seqType, String prefix) {
        return prefix + String.valueOf(SequenceGeneratorService.getNextSequence(seqType));
    }

    /**
     * 调用UniqueTableService方法获取序号
     * @param name 序号类型
     * @return
     */
    public static long getNextSequence(String name) {
        if (StringUtil.isEmpty(name)) {
            log.error("the sequence name is empty!");
            throw new BizException("DB00000002", "the sequence name is empty!");
        }
        UniqueTableService pkInfo = (UniqueTableService)keyList.get(name);
        if (pkInfo == null) {
            synchronized (keyList) {
                pkInfo = (UniqueTableService)keyList.get(name);
                if (pkInfo == null) {
                    pkInfo = (UniqueTableService) SpringContextUtil.getBean("UniqueTableService");
                    pkInfo.setPoolSize(POOL_SIZE);
                    pkInfo.setTabName(name);
                    keyList.put(name, pkInfo);
                }
            }
        }
        synchronized (pkInfo) {
            long retVal = pkInfo.getNextId();
            return retVal;
        }
    }
}
